package com.xiaoy.core.base.security.user.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.orm.Page;

import com.xiaoy.core.base.security.exception.UserDisabledException;
import com.xiaoy.core.base.security.role.entity.Role;
import com.xiaoy.core.base.security.user.dao.UserDao;
import com.xiaoy.core.base.security.user.entity.User;
import com.xiaoy.dao.DaoUtil;

@Service
public class UserService {
	
//	@Resource
//	private RoleService roleService;
//	
	@Resource
	private DaoUtil dao;
	
	@Resource
	private UserDao userDao;
	
	/**
	 * 个人的角色
	 * @param id
	 * @return
	 * TODO
	 */
	public List<Role> getRoleByUserId (long id) {
		
		String sql = "select r.* from sys_user_role ur,sys_role r where ur.user_id ="
				+ id;

		return (List<Role>) dao.query(Role.class, sql);
	}
	/**
	 * 包含组织机构中的角色k
	 * @param id
	 * @return
	 * TODO
	 */
	public List<Role> getAllRoleByUserId (long id) throws Exception {
		String sql = "select * from sys_user u ,sys_user_role ur,sys_org_user ou,sys_org_role orole"+
					"where u.id = ur.user_id and u.id = ou.user_id and ou.org_id = orole.org_id"+
					"and u.id = ?";
		return dao.query(Role.class,sql, id);
	}
	
	@Cacheable(value="serviceCache")  
	public Page<User> filterPage (Page<User> page) {
		return userDao.findPage(page, page.getFilters());
	}
	
	@CacheEvict(value="serviceCache",key="list") 
	public void clearCache(){
		
	}
	
	@Cacheable(value="serviceCache") 
	public User findBy (String name) {
		
		String where = " where 1=1 ";
		if (name != null && !"".equals(name)) {
			where += " and id = '"+name+"'";
		}
		String sql = "select * from sys_user "+where;
		return dao.query(User.class, sql).get(0);
	}
	
	public User getByUsername (String username)  throws Exception {
		System.out.println(username);
		List<User> users = userDao.findBy("username", username);
		if (users.size()>0) {
			User user = users.get(0);
			if ("0".equals(user.getEffect())) {
				throw new UserDisabledException(username + " is disabled ");
			}
			return user;
		}
		
		throw new UserDisabledException("not one user by "+username);
	}
	
	public List<User> getUsers () {
		return userDao.getAll();
	}
	
	@Transactional
	public void save (User user) {
		userDao.save(user);
	}
	
	public User get(long id){
		return userDao.get(id);
	}
}
